<?php
set_include_path("../include;include");
require_once '/util/globals.php';
require_once '/dao/Database.php';

/**
 * database access class for codeKeeper
 *
 * @author Thomas Crepain <contact@thomascrepain.be>
 */
class codeKeeperDAO
{
        const TABLENAME = 'codekeeper';

	/**
	 *
	 *
	 * @var Database
	 */
	private $db;

	/**
	 * unique instance of this class
	 * Singleton pattern
	 *
	 * @var Database
	 */
	private static $uniqueInstance;


	/**
	 * constructs the DAO
	 */
	private function __construct()
	{
		// get database
                $this->db = Database::getInstance();
	}

	/**
	 * gets instance of database
	 *
	 * @return GroupDAO
	 */
	public static function getInstance()
	{
		if(!isset(self::$uniqueInstance))
		{
			self::$uniqueInstance = new self();
		}

		return self::$uniqueInstance;
	}

	/**
	 * Returns the number of calls for the event
	 *
         * @param integer $eventkey
	 * @return String
	 */
	public function getCallvalueByEventkey(integer $eventkey)
	{
            $records = $this->db->getRecords("SELECT callvalue FROM " . self::TABLENAME . " WHERE eventkey = ?", array($eventkey));
            
            if(count($records) == 0) {
                $this->db->insert(self::TABLENAME, array("callvalue" => 0, "eventkey" => $eventkey));
                //$this->db->execute("INSERT INTO " . self::TABLENAME . " VALUES ('', 0, $eventkey)");
                $records[0]['callvalue'] = 0;
            }

            return $records[0]['callvalue'];
	}

        /**
	 * Saves the callvalue in the database
         *
         * @param integer $eventkey
	 */
	public function incrementCallvalueForEventKey(integer $eventkey)
	{
            $this->db->execute("UPDATE " . self::TABLENAME . " SET callvalue=callvalue+1 WHERE eventkey = ?;", array($eventkey));
            return $this->db->getVar("SELECT callvalue FROM " . self::TABLENAME . " WHERE eventkey = ?", array($eventkey));
	}
}

?>